import express from 'express'
import fs from 'node:fs'
import knex from 'knex'
import yaml from 'js-yaml'
import { filterParams } from './utils/index.js'

const baseConfig = yaml.load(fs.readFileSync('./base.yaml', 'utf8'))
const db = knex({
  client: 'mysql2',
  connection: {
    host: baseConfig.host,
    port: baseConfig.port,
    user: baseConfig.user,
    password: baseConfig.password,
    database: baseConfig.database
  }
});

const app = express()

// 支持post接口
app.use(express.json())

//查询接口 全部
app.get('/', async (req, res) => {
  filterParams(req.query)
  console.log('req查询', req.query, req.params, req.body);
  if (Object.keys(req.query).length === 0) {
    const data = await db('list').select().orderBy('id', 'desc')
    const total = await db('list').count('* as total')
    res.json({
      code: 200,
      data,
      total: total[0].total,
    })
  } else {
    const row = await db('list').select().where({ ...req.query })
    res.json({
      code: 200,
      data: row,
      total: row.length,
    })
  }
})
//单个查询 params
app.get('/user/:id', async (req, res) => {
  const row = await db('list').select().where({ id: req.params.id })
  res.json({
      code: 200,
      data: row
  })
})

//新增接口
app.post('/create', async (req, res) => {
  const { name, age, hobby } = req.body
  const detail = await db('list').insert({ name, age, hobby })
  res.send({
      code: 200,
      data: detail
  })
})

//编辑
app.post('/update', async (req, res) => {
  const { name, age, hobby, id } = req.body
  if (id) {
    const info = await db('list').update({ name, age, hobby }).where({ id })
    res.json({
      code: 200,
      data: info
    })
  } else {
    res.json({
      code: 400,
      data: '修改失败'
    })
  }
})
//删除
app.post('/delete', async (req, res) => {
  const { ids } = req.body;
  console.log(
    '%c ids: ',
    'background-color:#7ec050;padding:4px 8px;border-radius:2px;font-size:14px;color:#fff;font-weight:700;',
    ids
  )
  let info = null;
  if (Array.isArray(ids) && ids.length > 0) {
    info = await db('list').delete().whereIn('id', ids)
  } else {
    info = await db('list').delete().where({ id: req.body.ids })
  }
  res.json({
    code: 200,
    data: info
  })
})
const port = 3000

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})
